﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityBinder.Interface;

namespace EntityBinder.Xml
{
	class XmlWriter : IEntityWriter
	{
		public bool Indent { get; set; }

		private IEntityElement m_rootElement = null;

		internal XmlWriter()
		{
			Indent = false;
		}

		internal XmlWriter(IEntityElement _rule) : this()
		{
			m_rootElement = _rule;
		}

		public void Write(System.IO.Stream _outputStream, object _data)
		{
			Write(_outputStream, _data, m_rootElement);
		}

		public void Write(System.IO.Stream _outputStream, object _data, IEntityElement _rules)
		{
			if(_rules == null)
			{
				throw new EntityBinderException("XmlWriter", "Write", "Can not write object without any rules");
			}

			System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
			settings.Encoding = Encoding.UTF8;
			if (Indent)
			{
				settings.Indent = true;
				settings.IndentChars = "\t";
				settings.NewLineChars = "\n";
				settings.NewLineHandling = System.Xml.NewLineHandling.Replace;
			}
			using(System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(_outputStream, settings))
			{
				writer.WriteStartDocument();

				_rules.Write(_data, new XmlElementWriter(writer));

				writer.WriteEndDocument();
			}
		}
	}
}
